/**
 * COPYRIGHT HangZhou Trustway Technology Company Limited
 * All right reserved.
 */
package com.robam.cloud.component.componentfeign.initdata;

import com.robam.cloud.common.bean.common.Constant;
import com.robam.cloud.common.bean.restful.entity.RespMsg;
import com.robam.cloud.common.bean.restful.entity.ServiceException;
import com.robam.cloud.common.bean.usercenter.entity.LoginAccount;
import com.robam.cloud.common.bean.usercenter.entity.User;
import com.robam.cloud.common.util.StringUtil;
import com.robam.cloud.component.componentfeign.basefeign.FeignUserCenterBaseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description
 * @Author 薛铁琪
 * @CreateTime 2020-07-29 13:18
 * @Version 1.0
 */
@Component
public class CurrentAccountAndUserData {

    @Autowired
    FeignUserCenterBaseUtil feignUserCenterBaseUtil;
    @Autowired
    RedisTemplate redisTemplate;

    public LoginAccount getCurrentLoginAccount(HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader(Constant.TOKENNAME);
        String accountId = String.valueOf(redisTemplate.opsForValue().get(Constant.TOKENNAME + ":" + token));
        if (StringUtil.isEmpty(accountId)) {
            throw new ServiceException("登录超时请重新登录");
        }
        RespMsg respMsg = feignUserCenterBaseUtil.queryLoginAccount(Long.parseLong(accountId));
        if (respMsg == null) {
            throw new ServiceException("用户中心服务异常");
        }
        if (respMsg.getCode() != 200) {
            throw new ServiceException(respMsg.getMsg());
        }
        LoginAccount loginAccount = (LoginAccount) respMsg.getData();
        return loginAccount;
    }


    public User getCurrentUser(HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader(Constant.TOKENNAME);
        String accountId = String.valueOf(redisTemplate.opsForValue().get(Constant.TOKENNAME + ":" + token));
        if (StringUtil.isEmpty(accountId)) {
            throw new ServiceException("登录超时请重新登录");
        }
        RespMsg respMsg = feignUserCenterBaseUtil.queryUser(Long.parseLong(accountId));
        if (respMsg == null) {
            throw new ServiceException("用户中心服务异常");
        }
        if (respMsg.getCode() != 200) {
            throw new ServiceException(respMsg.getMsg());
        }
        User user = (User) respMsg.getData();
        return user;
    }
}
